﻿using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;

namespace DDD.Api.StartupExtensions
{
    public static class SwaggerExtension
    {
        public static IServiceCollection AddCustomizedSwagger(this IServiceCollection services, IWebHostEnvironment env)
        {
            if (!env.IsProduction())
            {
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("Swagger", new OpenApiInfo { Title = "UserCoreApi" });
                    options.CustomSchemaIds(x => x.FullName);

                    var basePath = AppDomain.CurrentDomain.BaseDirectory;

                    var files = Directory.GetFiles(basePath, "User.Core.Api.xml");
                    foreach (var file in files)
                        options.IncludeXmlComments(file, true);

                    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "Value: Bearer {token}",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,
                        Scheme = "Bearer"
                    });
                    options.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme{
                                Reference = new OpenApiReference {
                                            Type = ReferenceType.SecurityScheme,
                                            Id = "Bearer"}
                           },Array.Empty<string>()
                        }
                });
                });
            }

            return services;
        }

        public static IApplicationBuilder UseCustomizedSwagger(this IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (!env.IsProduction())
            {
                var url = string.Empty;

                app.UseSwagger(c =>
                {
                    c.RouteTemplate = "{documentName}/swagger.json";
                    c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = url } });
                });

                app.UseSwaggerUI(c => { c.SwaggerEndpoint("../Swagger/swagger.json", "UserCoreApi"); });

            }

            return app;
        }
    }
}
